package gw.com.android.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.app.ScreenShotListenManager;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.AdsData;
import gw.com.android.presenter.NoviceWelfarePresenter;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.dialog.BaseDialog;
import gw.com.android.ui.dialog.NoviceWelfarePopup;
import gw.com.android.ui.dialog.OrderPopWindow;
import gw.com.android.ui.dialog.SharePopWindow;
import gw.com.android.ui.me.FeedbackActivity;
import gw.com.android.ui.views.CommonTitleBar;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.AppActivities;
import www.com.library.app.FragmentsManagerUtil;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.dialog.BasePopWindow;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DeviceUtil;
import www.com.library.util.PermissionUtil;
import www.com.library.view.LoadingDialog;
import www.com.library.view.RecyclerClickListener;


public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected FragmentManager mFragmentManager = null;
    protected FragmentTransaction mFragmentTransaction = null;
    public String mCurrentTag = "";
    protected PushMsgTabFragment mCurrentFragment = null;
    @Nullable
    @BindView(R.id.common_title_bar)
    public CommonTitleBar mTitleBar = null;
    protected SoundPool mSoundPool;
    public boolean isResumed = false;
    private boolean windowFocus = false;
    /**
     * 添加等待框提示
     */
    private LoadingDialog mProgress;

    public PermissionUtil mAccessStoragePermission;
    private CompositeDisposable mCompositeDisposable;
    private ScreenShotListenManager manager;
    private SharePopWindow mScreenShotSharePopWindow;
    private Dialog screenShotDialog;
    private NoviceWelfarePopup noviceWelfarePopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((this instanceof WelcomeActivity) && (getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            Logger.e("重启 WelcomeActivity");
            finish();
            return;
        }
        if (AppMain.getApp().startFlag && !(this instanceof WelcomeActivity)) {
            Logger.e("重启 " + this.getClass().getSimpleName());
            ActivityManager.showWelcomeActivity(this);
            return;
        }
        AppMain.getApp().startFlag = false;
        setTransparentBar(false);
        AppMain.getApp().setThemeMode(this);
        setScreenOrien();
        GTConfig.instance().configureLanguage(this);
        setAcitivityParam();
        setContentView(getLayoutView());
        ButterKnife.bind(this);

        Logger.e("class on date " + this.getClass().getSimpleName());
        mFragmentManager = this.getSupportFragmentManager();
        FragmentsManagerUtil.instance().createStackByActivity(this);

        AppActivities.getSingleton().pushActivity(this);
        requestPermission(null);

    }

    /**
     * 设置透明状态栏
     * isTransparent 标识有些界面从状态栏处开始绘制ui
     */
    public void setTransparentBar(boolean isTransparent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //状态栏文字颜色设置为深色
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            decorView.setSystemUiVisibility(option);
            if (isTransparent) {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else {
                if (DeviceUtil.instance().FlymeSetStatusBarLightMode(getWindow(), true)) {
                    return;
                } else if (DeviceUtil.instance().MIUISetStatusBarLightMode(getWindow(), true)) {
                    return;
                } else {
                    getWindow().setStatusBarColor(Color.TRANSPARENT);
                }
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            if (isTransparent) {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else {
                if (DeviceUtil.instance().FlymeSetStatusBarLightMode(getWindow(), true)) {
                    return;
                } else if (DeviceUtil.instance().MIUISetStatusBarLightMode(getWindow(), true)) {
                    return;
                } else {
                    getWindow().setStatusBarColor(getResources().getColor(R.color.color_status_bar));
                }
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
            if (DeviceUtil.instance().FlymeSetStatusBarLightMode(getWindow(), true)) {
                return;
            } else if (DeviceUtil.instance().MIUISetStatusBarLightMode(getWindow(), true)) {
                return;
            }
        }
    }

    /**
     * 权限申请
     */
    public void requestPermission(final PermissionUtil.OnRequestPermissionResult result) {
        // 初始化 文件读写敏感权限，复制指标数据库
        mAccessStoragePermission = new PermissionUtil();
        mAccessStoragePermission.requestPermission(BaseActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, AppContances.REQUEST_PERMISSION_ACCESS_STORAGE, new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                if (null != result) {
                    result.onGranted();
                } else {
                    onPermissionGranted();
                }
            }

            @Override
            public void onRefused() {
                showToastPopWindow(AppMain.getAppString(R.string.permission_access_storage_notice));
                finish();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mAccessStoragePermission != null) {
            mAccessStoragePermission.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    protected void onPermissionGranted() {
        registerRxBus();
        initLayoutView();
        initViewData();
    }

    /**
     * 注册RxBus相关联的监听事件
     */
    public void registerRxBus() {
        Disposable quoteRegister = RxBus.getInstance().register(GTSConst.REPLY_QLOGIN_STATE + "", Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {

                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean isConnection) throws Exception {
                        quoteServerNotice(isConnection);
                    }
                });

        bindSubscription(quoteRegister);

        Disposable tradeRegister = RxBus.getInstance().register(GTSConst.REPLY_TLOGIN_STATE + "", Boolean.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {

                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean isConnection) throws Exception {
                        tradeServerNotice(isConnection);
                    }
                });

        bindSubscription(tradeRegister);
    }

    /**
     * 设置当前activity的一些系统属性
     */
    protected void setAcitivityParam() {

    }

    /**
     * 返回屏幕方向
     */
    public void setScreenOrien() {

    }

    /**
     * @return 返回当前界面加载的布局id
     */
    protected abstract int getLayoutView();

    /**
     * 初始化当前界面的控件
     */
    protected abstract void initLayoutView();

    /**
     * 初始化界面控件的值和条件
     */
    protected abstract void initViewData();

    /**
     * 气泡提示
     */
    public void showToastPopWindow(String errorMessage) {
        new ToastPopWindow(this, errorMessage).show();
    }

    /**
     * 显示指定的fragment
     */
    public void showFragment(PushMsgTabFragment mBaseFragment) {
        if (mFragmentManager == null) {
            mFragmentManager = this.getSupportFragmentManager();
        }
        mFragmentTransaction = mFragmentManager.beginTransaction();

        // 若当前fragment不存在则添加
        if (null == mFragmentManager.findFragmentByTag(mCurrentTag)) {
            mFragmentTransaction.add(R.id.contentFragment, mBaseFragment, mCurrentTag);
        }
        if (null != mCurrentFragment) {
            mFragmentTransaction.hide(mCurrentFragment);
        }
        mFragmentTransaction.show(mBaseFragment);
        mFragmentTransaction.commitAllowingStateLoss();
        mCurrentFragment = mBaseFragment;
        FragmentsManagerUtil.instance().setCurrentFragment(this, mCurrentFragment);
    }

    /**
     * RxBus注册事件管理类
     */
    public void bindSubscription(Disposable subscription) {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        this.mCompositeDisposable.add(subscription);
    }

    /**
     * 显示加载圈
     */
    public void showLoading() {
        if (null == mProgress || !mProgress.isShowing()) {
            mProgress = LoadingDialog.show(this, "", "");
            mProgress.setCancelable(false);
        }
    }

    /**
     * 隐藏加载圈
     */
    public void hideLoading() {
        if (null != mProgress) {
            mProgress.dismiss();
            mProgress = null;
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.e("class on onResume " + this.getClass().getSimpleName());
        // 屏幕常亮设置
        if (GTConfig.instance().getBooleanValue(GTConfig.PREF_KEEP_SCREEN, false)) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(BaseActivity.this);
        isResumed = true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    /**
     * 行情服务器监听调用的通知方法
     */
    public void quoteServerNotice(Boolean isConntion) {
        Logger.e(this.getClass().getSimpleName() + " quoteServerNotice " + isConntion);
        if (isConntion && isResumed && DataManager.instance().getLoadDataState(GTSConst.ZONE_TYPE_ALL + "")) {
            onSendQuote();
        }
    }

    /**
     * 交易服务器监听调用的通知方法
     */
    public void tradeServerNotice(Boolean isConntion) {

    }

    /**
     * 发送行情订阅
     */
    protected void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
    }

    @Override
    protected void onStop() {
        super.onStop();
        Logger.e("class on onStop " + this.getClass().getSimpleName());
        isResumed = false;
    }

    @Override
    public void finish() {
        super.finish();
        Logger.e("class on finish " + this.getClass().getSimpleName());
        /* Pop Activity off stack */
        AppActivities.getSingleton().popActivity(this);
        if (this.mCompositeDisposable != null) {
            this.mCompositeDisposable.clear();
        }
        FragmentsManagerUtil.instance().removeAllPushMsgTabFragment(this);

    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            Logger.e("class on onDestroy " + this.getClass().getSimpleName());
            if (this.mCompositeDisposable != null) {
                this.mCompositeDisposable.clear();
            }

            if (null != mFragmentManager) {
                mFragmentManager = null;
            }

            if (null != mFragmentTransaction) {
                mFragmentTransaction = null;
            }

            if (null != popWindow) {
                popWindow.hidden();
            }
            if (noviceWelfarePopup != null) {
                noviceWelfarePopup.hide();
            }
            if (mSoundPool != null) {
                mSoundPool.release();
            }
            if (null != LoadingDialog.instance() && LoadingDialog.instance().getOwnerActivity() != null && !LoadingDialog.instance().getOwnerActivity().isFinishing()) {
                LoadingDialog.instance().dismiss();
            }
            if (null != BaseDialog.instance() && BaseDialog.instance().getOwnerActivity() != null && !BaseDialog.instance().getOwnerActivity().isFinishing()) {
                BaseDialog.instance().dismiss();
            }
            if (null != BasePopWindow.instance() && BasePopWindow.instance().activity != null && !BasePopWindow.instance().activity.isFinishing()) {
                BasePopWindow.instance().hidden();
            }
            AppActivities.getSingleton().popActivity(this);
            FragmentsManagerUtil.instance().removeAllPushMsgTabFragment(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OrderPopWindow popWindow = null;

    /**
     * 订单成交提示
     */
    public void showOrderTips(BaseActivity activity, DataItemDetail mDealModel) {
        if (null != OrderPopWindow.instance() && OrderPopWindow.instance().hasShowing()) {
            Logger.e("showOrderTips 不显示");
            return;
        }
        Logger.e("showOrderTips 显示");
        popWindow = new OrderPopWindow();
        if (mTitleBar != null) {
            popWindow.initPopWindow(activity, mTitleBar);
        } else {
            popWindow.initPopWindow(activity, null);
        }
        popWindow.setTitleView(getOrderTips(mDealModel));
        popWindow.show();
        playSound(activity);
    }

    private String getOrderTips(DataItemDetail mDealModel) {
        StringBuilder m_spannableTitle = new StringBuilder();
        String prdName = DataManager.instance().getPrdName(mDealModel);
        /*限价开仓----停损开仓*/
        if (mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_APPLY_TYPE || mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_APPLY_STOP_TYPE) {
            m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_pending_transactions) + prdName);
            if (mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_APPLY_TYPE) {
                m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_limit_trade));
            } else if (mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_APPLY_STOP_TYPE) {
                m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_stop_trade));
            }
            /*止损*/
        } else if (mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_STOP_TYPE) {
            m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_transactions) + prdName + AppMain.getApp().getResources().getString(R.string.order_hint_losses_closing));
            /*止盈*/
        } else if (mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_LIMIT_TYPE) {
            m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_transactions) + prdName + AppMain.getApp().getResources().getString(R.string.order_hint_stop_earnings_closing));
            /*强平*/
        } else if (mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_FORCE_CLOSE_TYPE || mDealModel.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.SYS_ORDER_TYPE_FORCE_CLOSE_TYPE) {
            m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_pending_position_closing) + prdName + AppMain.getApp().getResources().getString(R.string.order_hint_position_closing));
        }

        m_spannableTitle.append(AppMain.getAppString(R.string.order_hint_lot, mDealModel.getString(GTSConst.JSON_KEY_VOLUME)));
        m_spannableTitle.append("@" + mDealModel.getString(GTSConst.JSON_KEY_DEALPRICE));

        Logger.e("当日成交::" + m_spannableTitle.toString());
        return m_spannableTitle.toString();
    }

    /**
     * 发出声音
     */
    private void playSound(final Context context) {
        if (GTConfig.instance().getBooleanValue(GTConfig.PREF_ORDER_NOTICE_SOUND, true)) {
            if (mSoundPool == null) {
                //当前系统的SDK版本大于等于21(Android 5.0)时
                if (Build.VERSION.SDK_INT >= 21) {
                    SoundPool.Builder builder = new SoundPool.Builder();
                    //传入音频数量
                    builder.setMaxStreams(2);
                    //AudioAttributes是一个封装音频各种属性的方法
                    AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
                    //设置音频流的合适的属性
                    attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
                    //加载一个AudioAttributes
                    builder.setAudioAttributes(attrBuilder.build());
                    mSoundPool = builder.build();
                }
                //当系统的SDK版本小于21时
                else {//设置最多可容纳3个音频流，音频的品质为500
                    mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 100);
                }
            }

            AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
            float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            final float volume = streamVolumeCurrent / streamVolumeMax;
            final int soundId = mSoundPool.load(context, R.raw.dingdong1, 1);
            mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                @Override
                public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSoundPool.play(soundId, volume,
                                    volume, 1, 0, 1f);
                        }
                    }, 20);
                }
            });

        }
        //震动
        if (GTConfig.instance().getBooleanValue(GTConfig.PREF_ORDER_NOTICE_SHAKE, true)) {
            // 参数：1、Map中取值 2、当前音量 3、最大音量 4、优先级 5、重播次数 6、播放速度
            Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            if (vibrator != null && vibrator.hasVibrator()) {
                long[] pattern = {100, 400, 100, 400}; // 停止 开启 停止 开启
                vibrator.vibrate(pattern, -1); // 重复两次上面的pattern 如果只想震动一次，index设为-1
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            windowFocus = true;
        }
        if (windowFocus && NoviceWelfarePresenter.getInstance().needShow()) {
            AdsData.PicData adData = NoviceWelfarePresenter.getInstance().getAdData();
            if (adData != null) {
                showNoviceWelfare(adData.title, adData.link);
            }
        }
    }

    /**
     * 新手福利小广告
     * 如不需要展示的activity，可重写此方法
     */
    public void showNoviceWelfare(String title, String link) {
//        if (noviceWelfarePopup == null && windowFocus) {//暂时不要这个小广告了
//            View decorView = getWindow().getDecorView();
//            noviceWelfarePopup = new NoviceWelfarePopup(this, decorView, title, link);
//            noviceWelfarePopup.show();
//        }
    }

    public void hideNoviceWelfare() {
        if (noviceWelfarePopup != null) {
            noviceWelfarePopup.hide();
        }
    }

}
